import { PlayerHeadUI, PlayerHeadUIPool } from '../etc/PlayerHeadUI';
import { util } from "../etc/Util";

@Component
export default class Appearance extends mw.Script {
    static onAppearanceCreated:Action1<Appearance> = new Action1()
    // 前后端都有
    static AppearanceMap: Map<number, Appearance> = new Map()
    // 绑定右手的槽位偏移
    static RightHandWeaponOffset: Transform = new Transform(
        new Vector(2, 1, 0),
        new Rotation(0, 90, -30),
        Vector.one
    )
    // 绑定腰间的槽位偏移
    static ButtocksWeaponOffset: Transform = new Transform(
        new Vector(-11, -21, 35),
        new Rotation(180, -68, 0),
        Vector.one
    )

    @mw.Property({ multicast: true, replicated: true, onChanged: 'onOwnerPlayerIDChanged' })
    ownerPlayerID: number
    // 玩家名称
    @mw.Property({ multicast: true, replicated: true, onChanged: 'onPlayerNameChanged' })
    playerName: string = ''

    ownerPlayer: Player
    headUI: PlayerHeadUI
    weaponGameObject: GameObject

    init(ownerPlayerID: number) {
        this.ownerPlayerID = ownerPlayerID
        Appearance.AppearanceMap.set(this.ownerPlayerID, this)
        Appearance.onAppearanceCreated.call(this)
    }

    private async onOwnerPlayerIDChanged() {
        Appearance.AppearanceMap.set(this.ownerPlayerID, this)
        this.ownerPlayer = await Player.asyncGetPlayer(this.ownerPlayerID)
        await this.ownerPlayer.character.asyncReady()
        // 更新头顶UI
        this.refreshHeadUI()
        // 佩戴武器
        this.onWeaponChanged()
    }

    private onWeaponChanged(){
        if(this.weaponGameObject){
            GameObjPool.despawn(this.weaponGameObject)
        }
        this.weaponGameObject = GameObjPool.spawn('230F4F6E', GameObjPoolSourceType.Scene)
        this.weaponGameObject.setCollision(CollisionStatus.Off)
        this.ownerPlayer.character.attachToSlot(this.weaponGameObject, HumanoidSlotType.RightHand)
        this.weaponGameObject.localTransform.position = Vector.zero
        this.weaponGameObject.localTransform.rotation = Rotation.zero
    }

    private onPlayerNameChanged() {
        this.refreshHeadUI()
    }

    private onVipStateChanged() {
        this.refreshHeadUI()
    }

    private onRankExpChanged() {
        this.refreshHeadUI()
    }

    private refreshHeadUI(){
        if (!this.ownerPlayer?.character?.isReady) return
        // if (!this.headUI) this.headUI = PlayerHeadUIPool.get()
        // this.headUI.setInfo(this.ownerPlayer.character, this.playerName)
    }

    protected onDestroy(): void {
        if (SystemUtil.isClient()) {
            if (this.weaponGameObject) {
                GameObjPool.despawn(this.weaponGameObject)
            }
            if (this.headUI) {
                PlayerHeadUIPool.giveBack(this.headUI)
            }
        }

        Appearance.AppearanceMap.delete(this.ownerPlayerID)
    }
}